﻿using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace ACSR.Core.Patterns.Proxies
{

    public abstract class BaseProxy<T> : RealProxy, IRemotingTypeInfo where T : class
    {
        private T _instance = null;

        public BaseProxy()
            : base(typeof(T))
        {
        }

        protected virtual T GetObject()
        {
            if (_instance == null)
            {
                _instance = (T)GetTransparentProxy();
            }
            return _instance;
        }

        public virtual bool CanCastTo(Type fromType, object o)
        {
            return true;
        }

        public string TypeName
        {
            get
            {
                return typeof(T).FullName;
            }
            set
            {
            }
        }

        protected abstract object InternalInvokeMethod(IMethodCallMessage methodMessage);


        public override IMessage Invoke(IMessage msg)
        {


            IMethodCallMessage methodMessage = (IMethodCallMessage)msg;
            //MethodBase method = methodMessage.MethodBase;
            object returnValue = InternalInvokeMethod(methodMessage);

            return new ReturnMessage(returnValue, methodMessage.Args,
                methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage);

        }
    }
}
